<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/04
 * Time: 17:52
 */

namespace Modules\Admin\Service;

use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\OrderPayRefundRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\OrderRepairstoreGoodsRepository;
use HiCommon\Service\PayService;

class OrderRepairstoreService
{
    /**
     * 获取分页数据
     */
    public function get_list(array $arr_search)
    {
        try {
            $map = self::check_order_status($arr_search);

            $arr_option['where'] = $map['where'];
            //$arr_option['with'] = ['shop', 'user', 'gtype'];
            $data_obj = OrderRepairstoreRepository::get_list($arr_option, $map['search']);
            $data = list_page_data($data_obj, $arr_search);

            foreach ($data['data'] as $key => &$value) {
                $value['order_type_msg'] = $value['order_type'] == 2 ? '代驾' : '自驾';
                $value['order_status'] = OrderRepairstoreRepository::orderStatus($value['status'], $value['pay_status']);
            }
            $shop_id = $map['where']['shop_id'];
            $data['d_num'] = OrderRepairstoreRepository::get_count(['status' => 0, 'pay_status' => 1, 'shop_id' => $shop_id]);//待处理订单数量
            $data['t_num'] = OrderRepairstoreRepository::get_count(['status' => 0, 'pay_status' => 3, 'shop_id' => $shop_id]);//申请退款订单数量

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 订单状态筛选条件
     */
    public function check_order_status($arr_search)
    {
        $search = [];
        $where['shop_id'] = get_shop_id();//商户id
        if (!empty($arr_search['order_number'])) {
            $where['order_number'] = $arr_search['order_number'];
        }
        if (!empty($arr_search['range'])) {
            $search['range'] = $arr_search['range'];
        }
        if (!empty($arr_search['range'])) {
            $search['range'] = $arr_search['range'];
        }
        if (!empty($arr_search['order_type'])) {
            $where['order_type'] = $arr_search['order_type'];
        }

        if (!empty($arr_search['status']) && $arr_search['status'] == '1') {//待支付
            $where['status'] = 0;
            $where['pay_status'] = 0;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '2') {//待处理
            $where['status'] = 0;
            $where['pay_status'] = 1;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '3') {//申请退款
            $where['status'] = 0;
            $where['pay_status'] = 2;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '4') {//已退款
            $where['status'] = 0;
            $where['pay_status'] = 3;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '5') {//已取消
            $where['status'] = 2;
        }

        return ['where' => $where, 'search' => $search];
    }

    /**
     * 保养订单列表
     */
    public function maintain_order_list(array $arr_search)
    {
        try {
            $map = self::check_order_status($arr_search);
            $search = $map['search'];
            $search['order_type'] = 3;

            $arr_option['where'] = $map['where'];
            //$arr_option['with'] = ['maintain_goods'];
            $data_obj = OrderRepairstoreRepository::get_list($arr_option, (array)$search);
            $data = list_page_data($data_obj, $arr_search);

            foreach ($data['data'] as $key => &$value) {
                $value['order_status'] = OrderRepairstoreRepository::orderStatus($value['status'], $value['pay_status']);
            }
            $shop_id = $map['where']['shop_id'];
            $data['d_num'] = OrderRepairstoreRepository::get_count_by_where(['status' => 0, 'order_type' => 3, 'pay_status' => 1, 'shop_id' => $shop_id]);//待处理订单数量
            $data['t_num'] = OrderRepairstoreRepository::get_count_by_where(['status' => 0, 'order_type' => 3, 'pay_status' => 3, 'shop_id' => $shop_id]);//申请退款订单数量

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 添加一条数据
     */
    public function add_one($arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {
            //添加
            $res = OrderRepairstoreRepository::add_one($arr_input)->toarray();
            if (empty($res)) {
                return hello_error('添加失败');
            }

            return hello_success('成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 查询一条数据
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }
            $arr_option['with'] = ['user'/*,'maintain_goods'*/];
            $order_boj = OrderRepairstoreRepository::get_one($n_id, $arr_option);
            if ($order_boj->first()) {
                $order_arr = $order_boj->toArray();
                $order_arr['state'] = OrderRepairstoreRepository::orderStatus($order_arr['status'], $order_arr['pay_status']);

                return hello_success('查询成功', $order_arr);
                /*if($order_arr['order_type'] == 3){//保养

                }else{// 服务
                    return hello_success('查询成功', $order_arr);
                }*/
            }

            return hello_error('失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改一条数据
     */
    public function edit_one(array $arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = OrderRepairstoreRepository::edit_one($arr_input);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改单个字段
     */
    public function change_one_state($arr_input)
    {
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }

            if (!empty($arr_input['pay_status'])) {//退款处理
                return self::refund($arr_input['id'], '维修店主动退款');
            }

            if ($arr_input['status'] == '1') {
                $arr_input['checked_at'] = date('Y-m-d H:i:s');//检修时间
            }

            $res = OrderRepairstoreRepository::edit_one($arr_input);
            if ($res === false) {
                return hello_error('操作失败');
            }

            return hello_success('处理成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 退款处理
     */
    public function refund($order_id, $remark = '')
    {
        $option['with'] = ['orderPayWechat'];
        $order = OrderRepairstoreRepository::get_one((int)$order_id, $option);
        if ($order->first()) {
            if ($order->pay_type == 1) {//微信支付
                $info = $order->toArray()['order_pay_wechat'];
                if (empty($info)) {
                    return hello_error('该订单未支付');
                }
                //检查是否有退款记录
                $is_have = OrderPayRefundRepository::get_count_by_where(['order_sn' => $info['order_sn']]);
                if (empty($is_have)) {
                    //修改订单状态为已退款
                    $arr_input = ['id' => $order_id, 'pay_status' => 3, 'refund_time' => date('Y-m-d H:i:s', time())];
                    $res = OrderRepairstoreRepository::edit_one($arr_input);
                    if ($res === false) {
                        return hello_error('操作失败');
                    }

                    //退款操作-整单
                    $s_refund_type = 'wechat_mini_pay';
                    $s_order_sn = $info['order_sn'];
                    $s_out_trade_no = $info['out_trade_no'];
                    $n_total_fee = intval($info['total_fee']);
                    $n_refund_fee = $n_total_fee;
                    $arr_option = ['refund_desc' => $remark];
                    return PayService::refund($s_refund_type, $s_order_sn, $s_out_trade_no, $n_total_fee, $n_refund_fee, $arr_option);
                } else {
                    return hello_error('该订单已退款');
                }
            } elseif ($order->pay_type == 2) {//支付宝

            }

            return hello_error('数据有误');
        }
        return hello_error('订单不存在');
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = OrderRepairstoreRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 定时任务三十分钟后取消订单(回收库存)
     */
    public function api_auto_cancle_repair($data)
    {
        $arr_input = ['id' => $data['id'], 'status' => 2];
        $res = OrderRepairstoreRepository::edit_one($arr_input);
        if ($data['order_type'] == 3) {
            //回收商品库存
            self::stock_back((int)$data['id']);
        }
        if ($res === false) {
            return hello_error('取消失败');
        }
        return hello_success('取消成功');
    }

    /**
     * 回收库存
     */
    public function stock_back(int $order_id)
    {
        $arr_option['where'] = ['order_repairstore_id' => $order_id];
        $arr_option['field'] = ['id', 'product_id', 'goods_num'];
        $list = OrderRepairstoreGoodsRepository::get_all($arr_option)->toArray();

        foreach ($list as $key => $value) {
            $id = $value['product_id'];
            $num = $value['goods_num'];
            GoodsProductRepository::increase_num($id, 'stock', $num);
        }
    }

    /**
     * 导出EXCEL （所有）
     */
    public function get_order_list(array $arr_search)
    {
        try {
            $map = self::check_order_status($arr_search);
            $arr_option['where'] = $map['where'];
            $search = $map['search'];
            $arr_option['with'] = ['user'];

            if ($arr_search['cate'] == '1') {
                $data = OrderRepairstoreRepository::get_all($arr_option, $search)->toArray();
            } else {
                $search['order_type'] = 3;
                $data = OrderRepairstoreRepository::get_all($arr_option, $search)->toArray();
            }
            $orderList = [];
            if ($data) {
                foreach ($data as $key => &$value) {
                    $value['order_type_msg'] = $value['order_type'] == 2 ? '代驾' : '自驾';
                    $value['order_status'] = OrderRepairstoreRepository::orderStatus($value['status'], $value['pay_status']);
                    $orderList[$value['order_status']][] = $value;
                }
            }

            return $orderList;
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }
}